<!--
  @author wangpeizhi
  @name 菜单管理
 -->
<template>
  <div class="menumanage">
    <div class="btn-container">
      <div class="btn-container-title">
        <span>菜单管理</span>
        <span v-if="breadList.length > 0">,当前选择</span>
        <span v-if="breadList.length" class="btn-container-title-select">{{ breadList.join('>') }}</span>
      </div>
      <div class="btn-container-btns">
        <el-button v-permission="'menumanageInsert'" class="filter-item" style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;" @click="handleCreateFirst">新增一级菜单</el-button>
        <template v-if="temp.parentId != ''">
          <el-button v-permission="'menumanageInsert'" class="filter-item" style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;" @click="handleCreate">新增下级</el-button>
          <el-button v-permission="'menumanageDelete'" class="filter-item" style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;" @click="handleDelete">删除</el-button>
        </template>
      </div>
    </div>
    <el-container class="enterpriseinfo">
      <split-pane split="vertical" :min-percent="0" :default-percent="32">
        <template slot="paneL">
          <div class="leftWrap">
            <div class="search-tree-select">
              <span>所属系统：</span>
              <el-select v-model="belongSystem" placeholder="请选择" style="width:225px" @change="changeSys">
                <el-option v-for="item in dict.CDFLMC" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
              </el-select>
            </div>
            <div class="search-tree-wrap">
              <el-input v-model.trim="treeName" style="width:75%" placeholder="菜单名称搜索" class="search-input" clearable @clear="clearSearchTree" />
              <el-button class="filter-item tree-filter" type="primary" @click="handleFilterTree">搜索</el-button>
            </div>
            <el-tree
              ref="qytree"
              v-loading="treeLoading"
              :data="treeData"
              :props="defaultProps"
              :expand-on-click-node="false"
              :default-expanded-keys="['-1']"
              class="dictTree"
              highlight-current
              node-key="id"
              :filter-node-method="filterNode"
              @node-click="handleUpdate"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span :class="['tag', data.type === 'CDLX01' ? 'gh' :(data.type === 'CDLX02' ? 'qy' : '')]">{{ (data.type === 'CDLX01') ? '菜单' : (data.type === 'CDLX02' ? '按钮' : '') }}</span>
              </span>
            </el-tree>
          </div>
        </template>
        <template slot="paneR">
          <el-main class="user-main">
            <div v-if="!isShow" class="ts-con">
              <div class="ts">
                <i class="el-icon-info" />
                <span v-html="showMsg" />
              </div>
            </div>
            <div v-else id="enterpriseinfo-container">
              <el-form ref="dataForm" v-loading="submitloading" :model="temp" :rules="rules" class="dataForm" label-position="right" label-width="150px" style="width: 400px;overflow: auto;">
                <el-form-item label="类型" prop="type">
                  <el-radio-group v-model="temp.type">
                    <el-radio v-for="v in dict.CDLX" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="标识" prop="code">
                  <el-input v-model.trim="temp.code" placeholder="请输入标识" />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                  <el-input v-model.trim="temp.name" placeholder="请输入名称" />
                </el-form-item>

                <template v-if="temp.type === 'CDLX01'">
                  <!-- <el-form-item label="菜单英文名称" prop="ename">
                <el-input v-model.trim="temp.ename" placeholder="请输入菜单英文名称" />
              </el-form-item>-->
                  <el-form-item label="所属类型" prop="belongType">
                    <el-radio-group v-model="temp.belongType">
                      <el-radio v-for="v in dict.JSLX" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="菜单图标标识" prop="img">
                    <el-input v-model.trim="temp.img" placeholder="请使用图标中的SVG Icons标识" />
                  </el-form-item>
                </template>
                <el-form-item label="请求路径" prop="url">
                  <el-input v-model.trim="temp.url" placeholder="请输入请求路径" />
                </el-form-item>
                <el-form-item label="排序">
                  <el-input v-model="temp.sort" placeholder="请输入排序号" />
                </el-form-item>
                <el-form-item>
                  <el-button style="padding: 8px 30px;" @click="isShow=false">取消</el-button>
                  <el-button v-permission="'menumanageUpdate'" style="padding: 8px 30px;" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-main>
        </template>
      </split-pane>
    </el-container>
  </div>
</template>

<script>
import { specialText, intwith, validateAlphabets } from '@/utils/validate'
import { getDictByCode, queryMenu, createFirst, insert, update, del, get } from '@/views/menu/api'
import { mapGetters } from 'vuex'
import permission from '@/directive/permission/index.js' // 权限判断指令
import splitPane from 'vue-splitpane'
export default {
  name: 'Menumanage',
  components: { splitPane },
  directives: { permission },
  data() {
    return {
      treeLoading: false,
      submitloading: false,
      comLoading: false,
      isShow: false,
      comOption: [],
      showMsg: '单击左侧菜单项进行维护',
      treeData: [],
      tradeList: [], // 行业列表
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      treeName: '',
      dialogStatus: '',
      parentId: '',
      temp: {
        parentId: '',
        code: '',
        sort: '',
        name: '',
        ename: '',
        img: '',
        belongSystem: '',
        belongType: '',
        type: '',
        url: '',
        id: ''
      },
      rules: {
        code: [{ required: true, message: '请输入标识', trigger: 'blur' }, { validator: specialText, trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }, { validator: specialText, trigger: 'blur' }],
        ename: [{ required: true, message: '请输入菜单英文名称', trigger: 'blur' }, { validator: validateAlphabets, trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        belongType: [{ required: true, message: '请选择机构类型', trigger: 'blur' }],
        img: [{ required: true, message: '请输入菜单图标标识', trigger: 'blur' }],
        sort: [{ validator: intwith, message: '排序应为零或正整数', trigger: 'blur' }]
      },
      superIdType: 0,
      dict: {
        CDLX: [], // 菜单类型
        JSLX: [], // 所属类型
        CDFLMC: []// 所属系统
      },
      rySeleteData: [],
      belongSystem: '',
      breadList: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    changeSys(val) {
      // this.$refs.PowerTreeFun.test(val)
    },
    refreshNodeBy(id) {
      const node = this.$refs.qytree.getNode(id) // 通过节点id找到对应树节点对象
      node.loaded = false
      node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
          if (code === 'CDFLMC') {
            console.log(this.dict[code])
            this.belongSystem = (this.dict[code].length > 0) ? this.dict[code][0].dictValue : ''
            this.getTreeData()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 清空搜索菜单
     */
    clearSearchTree() {
      this.treeName = ''
      this.$refs.qytree.filter('')
    },

    /**
     * 按菜单名称查询
     */
    handleFilterTree() {
      this.$refs.qytree.filter(this.treeName)
    },

    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    /**
     * 获取菜单树
     */
    getTreeData() {
      this.treeLoading = true
      return new Promise((resolve, reject) => {
        queryMenu({ belongSystem: this.belongSystem }).then(response => {
          this.treeLoading = false
          this.treeData = response.data.data
        }).catch(error => {
          reject(error)
          this.treeLoading = false
        })
      })
    },
    resetTemp() {
      this.temp = {
        parentId: '',
        code: '',
        sort: '',
        name: '',
        ename: '',
        img: '',
        belongSystem: this.belongSystem,
        belongType: '',
        type: '',
        url: '',
        id: ''
      }
      this.comOption = []
    },
    handleCreateFirst() {
      this.dialogStatus = 'create'
      this.isShow = true
      this.resetTemp()
      this.$nextTick(() => {
        this.temp.parentId = -1
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.isShow = true
      this.resetTemp()
      this.$nextTick(() => {
        this.temp.parentId = this.parentId
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 获取当前树节点和其父级节点
     */
    getTreeNode(node) {
      if (node) {
        if (node.label !== undefined) {
          this.breadList.unshift(node.label) // 在数组头部添加元素
          this.getTreeNode(node.parent) // 递归
        }
      }
    },
    handleUpdate(data, Node) {
      this.breadList = []
      this.getTreeNode(Node)
      if (data.id !== '-1') {
        this.parentId = data.id
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.1)'
        })
        return new Promise((resolve, reject) => {
          get(data.id).then((res) => {
            loading.close()
            this.temp = {
              parentId: res.data.data.parentId,
              code: res.data.data.code || '',
              ename: res.data.data.ename || '',
              belongType: res.data.data.belongType || '',
              sort: res.data.data.sort || '',
              belongSystem: this.belongSystem,
              name: res.data.data.name || '',
              type: res.data.data.type || '',
              img: res.data.data.img || '',
              url: res.data.data.url || '',
              id: res.data.data.id
            }
            this.dialogStatus = 'update'
            this.isShow = true
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }).catch(error => {
            reject(error)
            loading.close()
          })
        })
      }
    },
    handleDelete() {
      if (this.parentId) {
        this.delete(this.parentId)
      } else {
        this.$message({
          message: '请选择删除的项！',
          type: 'warning'
        })
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          if (this.temp.parentId == -1) {
            return new Promise((resolve, reject) => {
              createFirst(this.temp).then(() => {
                this.isShow = false
                loading.close()
                this.$message({
                  message: '创建成功！',
                  type: 'success'
                })
                this.getTreeData()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return new Promise((resolve, reject) => {
              insert(this.temp).then((res) => {
                this.isShow = false
                this.getTreeData()
                loading.close()
                this.$message({
                  message: '创建成功！',
                  type: 'success'
                })
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          }
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            update(this.temp).then((res) => {
              this.isShow = false
              loading.close()
              this.$message({
                message: '编辑成功！',
                type: 'success'
              })
              this.getTreeData()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },
    delete(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        del(ids).then((res) => {
          loading.close()
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.getTreeData()
          this.isShow = false
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
      })
    },
    updateTreeChildren(data) {
      const node = this.$refs.qytree.getNode(this.temp.parentId)
      if (!node) return
      const childNodes = node.childNodes
      for (let i = childNodes.length - 1; i >= 0; i--) {
        const child = childNodes[i]
        this.$refs.qytree.remove(child.data)
      }
      for (let i = 0, j = data.length; i < j; i++) {
        const child = data[i]
        this.$refs.qytree.append(child, node.data)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
$dark_gray: #bfced6;
.menumanage {
  padding: 10px;
  .el-dialog__wrapper {
    padding-bottom: 50px;
  }
  .enterpriseinfo {
    height: calc(100vh - 127px);
    padding: 0px;
		overflow: hidden;
		.vue-splitter-container{
			width: 100%;
		}
    .leftWrap {
      background: #fff;
      margin-right: 10px;
      padding: 10px;
			height: 100%;
			overflow-y: auto;
      .search-tree-select {
        margin-bottom: 10px;
      }
      .search-tree-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .tree-filter {
          padding: 10px 18px;
        }
      }
      .el-tree-node__content {
        margin-top: 10px;
      }
      .tag {
        font-size: 12px;
        border-radius: 4px;
        padding: 2px 4px;
        color: #fff;
        &.gh {
          color: #ff7474;
          border: 1px solid #ff7474;
        }
        &.qy {
          color: #2fbcfb;
          border: 1px solid #2fbcfb;
        }
        &.bm {
          color: #ffa11c;
          border: 1px solid #ffa11c;
        }
      }
      .el-tree-node__expand-icon.expanded {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      .el-icon-caret-right:before {
        content: '\E7A0';
        font-size: 14px;
      }
      .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
        content: '\E7A2';
        font-size: 14px;
      }
    }
    .user-main {
      padding: 10px;
      position: relative;
      background-color: #fff;
			height: 100%;
			overflow-y: auto;
      .ts-con {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        background: white;
        .ts {
          line-height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-top: -15px;
          margin-left: -110px;
          width: 210px;
          text-align: center;
          background: white;
          border-radius: 2px;
          box-shadow: 1px 1px 5px #e0dbdb;
          font-size: 14px;
          font-family: Microsoft Yahei In-Bold, Microsoft Yahei,
            Apple LiGothic Medium;
          color: #222222;
        }
      }
    }
  }
  .sysconfig-search {
    background-color: #fff;
    padding: 5px 10px;
    margin-bottom: 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 10px;
      }
    }
    .search-input {
      width: 78%;
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }
  .btn-container {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: 600;
      color: rgba(51, 51, 51, 1);
      .btn-container-title-select {
        @include font-color($mainColor);
      }
    }
  }
}
</style>
